package org.mtmi.ui.scenes;

import java.util.List;

import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.mtmi.ui.IMG;
import org.mtmi.ui.M;
import org.mtmi.ui.controls.IContentProvider;
import org.mtmi.ui.controls.ILabelProvider;
import org.mtmi.ui.controls.ListView;
import org.mtmi.ui.controls.listeners.ISelectionListener;
import org.mtmi.ui.controls.listeners.SelectionEvent;
import org.mtmi.ui.controls.popups.AbstractButtonPopup;
import org.mtmi.ui.drawables.IDrawable;
import org.mtmi.ui.layouts.LayoutData;

/**
 * Popup to choose the scene background image
 */
public class ChooseSceneBackgroundPopup extends AbstractButtonPopup implements ISelectionListener
{
	
	private static class LabelProvider implements ILabelProvider
	{
		@Override
		public IDrawable getImage(Object element) {
			if( element instanceof String ) {
				//as it's background: must reduce size:
				return IMG.GetD( (String)element, 1/8f );
			}
			return null;
		}

		@Override
		public String getText(Object element) {
			//no text here
			return null;
		}
	}
	
	private class ContentProvider implements IContentProvider
	{
		@Override
		public Object[] getElements(Object input) {
			List<String> keys = IMG.GetSceneBackgroundKeys();
			return keys.toArray();
		}
		
	}
	
	private ListView lv_items;
	private String current_key;
	
	public ChooseSceneBackgroundPopup( Scene scene,int flags ) {
		this( scene, "Choose Scene Background:", flags );
	}
	
	public ChooseSceneBackgroundPopup( Scene scene, String title, int flags ) {
		super( scene, title, flags );
	}
	
	public String getBackgroundKey() { return current_key; }
	
	@Override
	public Rectangle createContents( Scene scene ) {
		
		lv_items = new ListView( scene, getFlags()&M.SCENE_EDITOR_CONTROL );
		lv_items.addSelectionListener( this );
		lv_items.setLabelProvider( new LabelProvider() );
		lv_items.setContentProvider( new ContentProvider() );
		lv_items.setInput( this );
		
		/*List<String> keys = IMG.GetSceneIconKeys();
		int ncol = keys.size()/5;
		if( ncol<1 ) ncol=1; else if( ncol > 5 ) ncol = 5;*/
		lv_items.setColumnCount( 3 );
		
		current_key = scene.getBackgroundKey();
		lv_items.setSelection( current_key );
		
		Point sz = lv_items.computeSize( new LayoutData(scene) );
		Point s = scene.getSize();
		int w = sz.x;
		int h = s.y/2;
		int x = (s.x-w)/2;
		int y = (s.y-h)/2;
		lv_items.setBounds( x, y, w, h );
		
		return new Rectangle( x, y, w, h );
	}
	
	@Override
	protected void terminate( int id ) {
		lv_items.dispose();
		super.terminate( id );
	}
	
	@Override
	public void selectionChanged( SelectionEvent e ) {
		current_key = (String)e.selection;
	}

	@Override
	public void selectionConfirmed(SelectionEvent e) {
		current_key = (String)e.selection;
		terminate( OK );
	}
	
}
